import { useEffect, useRef, useState } from "react";
import styles from "./index.module.scss";
import useWebsocked from "../../hooks/useWebsocked";
import { Button, Input } from "antd-mobile";
function Services() {
  const user_id = 10;
  const server_id = 300;
  const [list, setList] = useState([]);
  const [value, setValue] = useState("");
  const { ws } = useWebsocked(user_id, server_id);
  const main = useRef(null)
  useEffect(() => {
    // 连接成功
    ws.onopen = function () {
      console.log("连接成功");
      // 连接成功立即要数据列表
      ws.send(JSON.stringify({ type: "getChatList" }));
    };

    ws.onmessage = (e) => {
      const { type, data } = JSON.parse(e.data);
      if (type == "getChatList") {
        setList(data);
      } else if (type == "addMessage") {
        setList((val) => {
          return [...val, data];
        });
        // 添加完消息，将输入框清空
        setValue("");
      }
    };
  }, []);
  // 发送消息
  const sendMessageFn = () => {
    ws.send(
      JSON.stringify({
        type: "addMessage",
        data: { message: value, type: "text" },
      })
    );
    setValue('')
  };
  useEffect(() => {
    main.current.scrollTop = 10000
  }, [list])
  return (
    <div className={styles.box_wroe}>
      <div ref={main} className={styles.main_wroe}>
        {list.map((item, index) => {
          return (
            <div
              key={index}
              className={item.user_id == user_id ? styles.chart_right : styles.chart_left}
            >
              <img src={item.user_id == user_id ? item.user_avatar : item.other_avatar} />
              <p>{item.message}</p>
            </div>
          );
        })}
      </div>

      <div className={styles.footer_wroe}>
        <Input
          className={styles.input}
          value={value}
          onEnterPress={sendMessageFn}
          onChange={(val) => {
            setValue(val);
          }}
        />
        <Button disabled={!value} onClick={sendMessageFn}>
          发送
        </Button>
      </div>
    </div>
  );
}

export default Services;
